<?php

namespace App\Services;

use App\Models\User;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;

class MessageService
{
    // 获取消息数据
    public static function getList($userInfo, $type = 1, $page = 1, $pageSize = 10)
    {
        $sqlObj = DB::table('message_record as p')
            ->select('p.id', 'p.status', 'p.created_at', 'm.title', 'm.content', 'm.send_type', 'm.type')
            ->leftJoin('message as m', 'm.id', '=', 'p.message_id');
        $sqlObj->where('p.status', '!=', -1);
        $sqlObj->where('p.recipient_id', $userInfo['id']);
        $sqlObj->where('p.type', 1);
        if (!empty($type)) {
            $sqlObj->where('m.type', $type);
        }

        $count = $sqlObj->count();
        $rel = PageService::getPageData($sqlObj, $page, $pageSize);


        if ($rel) {
            foreach ($rel as $k => $value) {
                $rel[$k]['id'] = (int)$value['id'];
                $rel[$k]['status'] = (int)$value['status'];
                $rel[$k]['start_time'] = date("Y-m-d H:i:s", strtotime($value['created_at']));
                unset($rel[$k]['created_at']);
            }
        }

        return PageService::formatPageData($rel, $page, $pageSize, $count);
    }

    //修改消息状态
    public static function msgChangestatus($user, $ids, $status = 1)
    {
        if (!isset($ids) || empty($status)) {
            return error_exit(SysCode::INTERNAL_SERVER_ERROR);
        }
        $rel = DB::table("message_record")->whereIn('id', $ids)->where('recipient_id', $user['id'])->update(['status' => $status]);

        if (!$rel) {
            return error_exit(SysCode::MESSAGE_CHANGE_STATUS);
        }
        return [];
    }
}
